/*************************************
Copyright 2011 Chinua Iloabachie, Pradnya Khutafale, Siyi Liu, Junichi Suzuki, and The University of Massachusetts, Boston (http://code.google.com/p/tabletuml/)


Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 
*************************************/



package touchMe.Draw;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import touchMe.Draw.R;
import touchMe.Util.AlertMessageBox;
import touchMe.Util.DiagramFileHandler;
import touchMe.Util.DiagramManager;
import touchMe.baseClass.Constants;
import touchMe.baseClass.Diagram;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class AndroidExplorer extends ListActivity {
	private String tag="TouchMe";
	private List<String> item = null;
	private List<String> path = null;
	private String root="/";
	private TextView myPath;
	private Button saveButton;
	private Button cancelButton;
	private EditText filenameedit;
	private TextView filenameLabel;
	private static String filePath;
	
	 
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.androidexp);
        setExplorerMode();
        myPath = (TextView)findViewById(R.id.path);
        getDir(root);
    }
    private void setExplorerMode() {
		if (Constants.explorerMode == Constants.OPEN)// explorer in open mode
		{
			setVisibilities(View.INVISIBLE);
			
		} else {
			setVisibilities(View.VISIBLE);
			setListeners();
		}

	}

	/**
	 * This method set listeners for save, cancel button and input text field
	 * used for entering filename
	 */

	private void setListeners() {

		this.filenameedit.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				return;
			}
		});

		this.cancelButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});

		this.saveButton.setOnClickListener(onSaveClick());// end save button
		// finish();
	}
	private OnClickListener onSaveClick() {
		OnClickListener v = new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Diagram diagram = Diagram.getInstance();
				Log.d(Constants.TAG,
						"Save Button Clicked on Android Explorer..");
				// SAVE FILE
				String newFileName;
				String mPath = AndroidExplorer.filePath;
				// If it is new file or save As mode then get filename from
				// input box
				if (diagram.isNewDiagram()
						|| Constants.explorerMode == Constants.SAVEAS)
					newFileName = filenameedit.getText().toString();
				else
					newFileName = diagram.getFilename();
				
				if (newFileName.length() > 0)// && !diagram.isNewDiagram())
				// || (newFileName==null && diagram.isNewDiagram()) )// if
				// filename entered
				{
					// filename should begin with a character
					if ((newFileName.charAt(0) >= 'a' && newFileName.charAt(0) <= 'z')
							|| (newFileName.charAt(0) >= 'A' && newFileName
									.charAt(0) <= 'Z')) 
					{
						if (!newFileName.endsWith(".uxf"))// filename .uxf not
					    newFileName = newFileName + ".uxf";// then attach
																// extention
						newFileName = filePath + "/" + newFileName;
						Log.d(Constants.TAG, "Saving File..");
						Diagram.getInstance().setFilename(newFileName);
						boolean result = DiagramFileHandler.writeDiagram(
								newFileName, Diagram.getInstance());
						if (result)// if successfully saved
						{
							DiagramManager.getUmlDiagram().setNewDiagram(false);
							Toast.makeText(getApplicationContext(),
									"File Saved", Toast.LENGTH_LONG).show();
							Intent intent = new Intent(AndroidExplorer.this,
									TouchMe.class);
							Log.d(tag, "Starting again touchMe after save..");
							intent.putExtra(TouchMe.filePath,
									AndroidExplorer.filePath);
							
							startActivity(intent);
							
							//android.os.Process.killProcess(android.os.Process.myPid());
							//v.invalidate();
							//finish();
						}// end result
						else
						{
							showErrMessageBadFile(v,"Error saving file","Try using a different filename or directory");	
						}
					}// end a-z
					else 
						//AlertMessageBox.getOKAlertBox(getApplicationContext(),"Error!! Please enter filename begining with a character"
							//	,"Enter File Name").show();
						showErrMessageBadFile(v,"Error!! Please enter filename begining with a character"
							,"Enter File Name");
                    // end else
				}// end filename entered
				else {
					showErrMessageBadFile(v," Error!! File name cannot be blank .. enter file name",
							"Enter file name");
					// display error message
				}
				// finish();
			}// end onCLick

		};// endsaveClick

		// finish();
		return v;
	}


    //displays only file you can read
    private void getDir(String dirPath)
    {
    	myPath.setText("Location: " + dirPath);
    	filePath = dirPath;
    	item = new ArrayList<String>();
    	path = new ArrayList<String>();
    	
    	File f = new File(dirPath);
    	File[] files = f.listFiles();
    	
    	if(!dirPath.equals(root))
    	{

    		item.add(root);
    		path.add(root);
    		
    		item.add("../");
    		path.add(f.getParent());
            
    	}
    	
    	for(int i=0; i < files.length; i++)
    	{
    			File file = files[i];
    			if(file.canRead()){
	    			path.add(file.getPath());
	    			if(file.isDirectory())
	    				item.add(file.getName() + "/");
	    			else{
	    				String fname=file.getName();
	    				//if(fname.substring(fname.length()-3).equalsIgnoreCase("uxf"))
	    				//String str=fname.substring(fname.length()-3);
	    				//if(str.equalsIgnoreCase("uxf"))
	    					item.add(fname);
	    			}
    			}
    	}

    	ArrayAdapter<String> fileList =
    		new ArrayAdapter<String>(this, R.layout.row, item);
    	setListAdapter(fileList);
    }

    /** This method displays alert box
	 * 
	 * @param v
	 * @param message
	 * @param toastMessage
	 */
	private void showErrMessageBadFile( View v,String message,final String toastMessage)
	{
		AlertDialog.Builder alertbox=	new AlertDialog.Builder(this);
		alertbox.setMessage(message);
		 alertbox.setNeutralButton("OK", new DialogInterface.OnClickListener() 
		 {
           public void onClick(DialogInterface arg0, int arg1) 
             {
   	    //replace this with the save dialog
            Toast.makeText(getApplicationContext(), toastMessage, Toast.LENGTH_SHORT).show();
             //newFile();
             }//end onClick
         }).show();//end dialoginterface
       
	}
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		
		File file = new File(path.get(position));
		
		if (file.isDirectory())
		{
			if(file.canRead())
				getDir(path.get(position));
			else
			{
				new AlertDialog.Builder(this)
				.setIcon(R.drawable.icon)
				.setTitle("[" + file.getName() + "] folder can't be read!")
				.setPositiveButton("OK", 
						new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
							}
						}).show();
			}
		}
		else
		{
			if(Constants.explorerMode==Constants.OPEN)
			{
			String ext=file.getName().substring(file.getName().length()-3);
			Diagram.getInstance().setFilename(file.getAbsolutePath());
			if(ext.equalsIgnoreCase("uxf")){//open DrawClassDiagram
				Intent intent=new Intent(AndroidExplorer.this, TouchMe.class);
				Log.d(tag,"path"+file.getAbsolutePath());
				intent.putExtra(TouchMe.filePath,file.getAbsolutePath());
				//this.finish();
		    	startActivity(intent);
		    	//android.os.Process.killProcess(android.os.Process.myPid());
		    	//v.invalidate();
		    	//l.invalidate();
		    	//finish();
			}else{
				new AlertDialog.Builder(this)
				.setIcon(R.drawable.icon)
				.setTitle("[" + file.getName() + "]  is not a TouchMe file")//,"+file.getAbsolutePath()+"
				.setPositiveButton("OK", 
						new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
							}
						}).show();
			   }
			}//end open mode	
		}
	}
	
	private void setVisibilities(int visibility)
	{
		saveButton = (Button) findViewById(R.id.bt_save_as);
		saveButton.setVisibility(visibility);
		cancelButton = (Button) findViewById(R.id.bt_cancelsaveas);
		cancelButton.setVisibility(visibility);// 4= invisible

		filenameedit = (EditText) findViewById(R.id.savefilename);
		filenameedit.setVisibility(visibility);// 4= invisible

		filenameLabel = (TextView) findViewById(R.id.filelabel);
		filenameLabel.setVisibility(visibility);// invisible
	}
	/*
	 public void finish() {
		 Log.d(Constants.TAG, "Finish..");
		// super.finish();
	 }
	 public void terminate() {
		 Log.d(Constants.TAG, "Terminate..");
		 //super.finish(); 
	 }
	*/
}